package com.demo.config.datasource.annotation;

import com.demo.filter.RequestContextHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import javax.sql.DataSource;


/**
 * @author wangfengchen
 */
@Slf4j
public class DynamicRoutingDataSource extends AbstractRoutingDataSource {

  @Override
  protected Object determineCurrentLookupKey() {
    String requestId = RequestContextHelper.get().getRequestId();
    // 从 ThreadLocal 获取数据源标识
    String key = DynamicDataSourceContextHolder.getDataSourceKey();
    // 如果没有手动设置数据源，使用默认数据源
    if (key == null) {
      key = DynamicDSEnum.MASTER.getDesc();
      DynamicDataSourceContextHolder.setDataSourceKey(key);
    }
    log.info("requestId = {}，DynamicRoutingDataSource determined key = {}", requestId, key);
    return key;
  }

  @Override
  protected DataSource determineTargetDataSource() {
    String requestId = RequestContextHelper.get().getRequestId();
    DataSource dataSource = super.determineTargetDataSource();
    log.info("requestId = {}，DynamicRoutingDataSource target datasource = {}", requestId, dataSource);
    return dataSource;
  }


}